package com.foodie.service;
import com.foodie.dao.DB;
import com.foodie.entity.User;
import java.util.List;
import java.util.Map;


public class UserService {
    public User login(String account, String password) {
        List<Map<String, Object>> result = DB.executeQuery("select * from t_user where user_id = ? and USER_PWD = ? ", account, password);
        User user = null;
        if (result != null) {
            for (Map<String, Object> temp : result) {
                user = new User();
                user.setId((Integer) temp.get("ID"));
                user.setUser_id((String) temp.get("USER_ID"));
                user.setUser_pwd((String) temp.get("USER_PWD"));
                user.setName((String) temp.get("NAME"));

            }
        }
        return user;
    }

    public User getUserByToken(String token) {
        List<Map<String, Object>> result = DB.executeQuery("select * from t_user where token = ?", token);
        User user = null;
        if (result != null) {
            for (Map<String, Object> temp : result) {
                user = new User();
                user.setName((String) temp.get("NAME"));
            }
        }
        return user;
    }

    //    注册用户
    public User register(User user) {
        try {
            int a = DB.executeUpdate("insert into t_user(name, user_id, sex ,phone, user_pwd)"
                            + "values(?,?,?,?,?)",
                    user.getName(),
                    user.getUser_id(),
                    user.getSex(),
                    user.getPhone(),
                    user.getUser_pwd());
            if (a == -1) {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return user;
    }

    /**
     * 判断账号是否存在
     *
     * @param account
     * @return
     */
    public boolean checkUser(String account) {
        return !DB.executeQuery("select count(*) as count from t_user where USER_ID = ?", account).get(0).get("count").toString().equals("0");
    }

    public void setToken(String token, Integer id) {
        DB.executeUpdate("update t_user set token = ? where ID = ?", token, id);
    }

    public void deleteToken(String token) {
        UserService userService = new UserService();

        DB.executeQuery("updtae t_user set TOKEN = '' where TOKEN = ?", token);
    }
}
